package com.raising.modules.sys.service;

import com.raising.framework.service.CrudService;
import com.raising.modules.sys.dao.UserDao;
import com.raising.modules.sys.entity.Organization;
import com.raising.modules.sys.entity.Role;
import com.raising.modules.sys.entity.User;
import com.raising.utils.JCacheUtils;
import com.raising.utils.JStringUtils;
import com.raising.utils.PasswordEntity;
import com.raising.utils.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 用户服务
 * @author gaoy
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserService extends CrudService<UserDao, User> {

	@Autowired
	private PasswordUtils passwordUtils;

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private OrganizationService organizationService;

	@Transactional(rollbackFor = Exception.class)
	public int insertAndUpdate(User user){
		if(user.getIsNewId()){
			//新建
			user.setStatus("1");
			user.preInsert(null);
			dao.insert(user);
		} else {
			//编辑
			user.preUpdate(null);
			dao.update(user);
		}
		return 1;
	}
	/**
	 * 修改密码
	 * 
	 * @param userId
	 * @param newPassword
	 */
	@Transactional(rollbackFor = Exception.class)
	public void changePassword(String userId, String password,
			String newPassword) throws RuntimeException{
		User user = dao.get(userId);
		//加密后的老密码
		String oldPassword = user.getPassword();
		//加密后的输入的密码
		String myPassword = passwordUtils.getPassword(password,user.getSalt());
		if ( oldPassword!=null && oldPassword.equals(myPassword)) {
			PasswordEntity passwordEntity = passwordUtils.encryptPassword(newPassword);
			user.setPassword(passwordEntity.getPassword());
			user.setSalt(passwordEntity.getSalt());
			save(user);
		} else {
			throw new RuntimeException("原密码错误");
		}
	}

	/**
	 * 修改登录密码
	 * @param user
	 * @param newPassword
	 */
	@Transactional(rollbackFor = Exception.class)
	public void changePassword(User user,String newPassword) throws Exception{
		PasswordEntity passwordEntity = passwordUtils.encryptPassword(newPassword);
		user.setPassword(passwordEntity.getPassword());
		user.setSalt(passwordEntity.getSalt());
		save(user);
	}

	/**
	 * 根据用户名查找其角色
	 * 
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public Set<String> findRoles( List<String> roleIds) {
		Set<String> set = roleService.findRoles(roleIds.toArray(new String[0]));
		if(set==null||set.isEmpty()){
			return Collections.emptySet();
		}
		return set;
	}
	/**
	 * 获取指定用户的角色对象集合
	 * @param userId 用户名
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public List<Role> findRolesOfUser(String userId) {
		User user = get(userId);
		if (user == null) {
			return Collections.emptyList();
		}
		List<Role> roles = new ArrayList<Role>();
		for (String roleId: user.getRoleIds()) {
			roles.add(roleService.get(roleId));
		}
		return roles;
	}

	/**
	 * 根据用户名查找其权限
	 * 
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public Set<String> findPermissions(List<String> roleIds) {
		Set<String> set = roleService.findPermissions(roleIds.toArray(new String[0]));
		if(set==null||set.isEmpty()){
			return Collections.emptySet();
		}
		return set;
	}

	/**
	 * 根据登录名和用户类型获取用户
	 * @param userName
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public User getUserByUserName(String userName) {
		if(JStringUtils.isBlank(userName)){
			return null;
		}
		User user = null;
		try {
			user = (User) JCacheUtils.get(userName);
			if(user==null){
				user = dao.getUserByUserName(userName);
				if(!user.isAdmin()){
					if( user.getOrganization()!=null && !"".equals(user.getOrganization())){
						//查找上级组织机构
						Organization org = organizationService.get(user.getOrganization().getParentId());
						if(org!=null){
							user.getOrganization().setParentParentIds(org.getParentIds());
						}else{
							user.getOrganization().setParentParentIds("----");
						}
					}
				}
				JCacheUtils.put(userName,user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}
	/**
	 * 根据登录名获取用户:每次都查询数据库
	 * @author peijs
	 * @param userName
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public User selectUserInfoByUserName(String userName) {
		return dao.getUserByUserName(userName);
	}

	/**
	 * 获取用户列表
	 * @param users
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public List<Map> getUsers(String[] users){
		return dao.getUsers(users);
	}
	/**
	 * 更新用户登录信息
	 * @author gaoy
	 * 2017 2017-5-22 上午11:07:51
	 * @param userId
	 * @param ip
	 * @param loginDate
	 */
	public void updateLoginInfo(String userId,String ip,Date loginDate){
		dao.updateLoginInfo(userId,ip,loginDate);
	}
	
	/**
	 * 更新用户状态
	 * @author fangl
	 * 2017-5-24 上午11:36:43 
	 * @param user
	 * @return
	 */
	public int updateStatus(User user){
		return dao.updateStatus(user);
	}

	/**
	 * 更新用户冻结状态
	 * @author GaoYuan
	 * @param userId
	 * @param locked
	 * @return
	 */
	public int updateLocked(String userId,int locked){
		return dao.updateLocked(userId,locked);
	}

	/**
	 * 根据单个角色或机构查询用户列表
	 * @author GaoYuan
	 * @datetime 2017/10/25 上午9:32
	 * @param roleId 角色标识
	 * @param orgId  所属机构标识
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public List<User> findListByRoleId(String roleId,String orgId){
		return dao.findListByRoleId(roleId,orgId);
	}
	/**
	 * 根据所属机构查询用户信息
	 * caow
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public List<User> selectUserInfoTo(User user){
		return dao.selectUserInfoTo(user);
	}
	/**
	 * 更新用户头像
	 * @author shimj
	 * 2017-6-1 上午11:36:43 
	 * @param user
	 * @return
	 */
	@Transactional(readOnly = true,rollbackFor = Exception.class)
	public int updateHeadImg(User user){
		return dao.updateHeadImg(user);
	}


}
